package cn.tj212.xiaoyin.web.auth;

import cn.tj212.xiaoyin.common.util.JsonUtil;
import cn.tj212.xiaoyin.common.web.HttpHelper;
import cn.tj212.xiaoyin.common.web.JsonView;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * shiro
 */
public class AuthFilter extends FormAuthenticationFilter {

    private static final Integer SHIRO_TIME_OUT=1001;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest= (HttpServletRequest) request;
        //获取请求路径
        String login=httpServletRequest.getServletPath();
        //判断请求路径是否是登录页，是就放行
        if (login.equals("/index.html")){
            return true;
        }
        //获取当前登录用户
        Subject subject=getSubject(request,response);
        //判断该用户是否授权
        if (subject.isAuthenticated()){
            return true;
        }
        //判断是否为ajax请求
        if (HttpHelper.isAjax(httpServletRequest)){
            JsonView jv=new JsonView();
            jv.setMessage("shiro登录超时!");
            jv.setErrcode(SHIRO_TIME_OUT);
            HttpServletResponse httpServletResponse= (HttpServletResponse) response;
            PrintWriter pw=httpServletResponse.getWriter();
            response.setContentType("application/json");
            pw.write(JsonUtil.toJson(jv));
            pw.flush();
            pw.close();
        }else {
            saveRequestAndRedirectToLogin(request, response);
        }
        return false;
    }
}
